package com.yunchang.springboot.service.AmazonAdvert;

import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.amazonAdvert.*;
import com.yunchang.springboot.mapper.shop.AreaMapper;
import com.yunchang.springboot.mapper.shop.ProfileMapper;
import com.yunchang.springboot.mapper.shop.RefreshTokenMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.*;
import com.yunchang.springboot.models.DO.ErrorDateDO;
import com.yunchang.springboot.models.DO.RefreshTokenDO;
import com.yunchang.springboot.models.DO.ShopAreaProfile;
import com.yunchang.springboot.utils.APICallsUtil;
import com.yunchang.springboot.utils.CryptoUtil;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.amazon.AmazonAdvertApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Component
@Slf4j
public class AmazonAdvertBrandsReportDataProcessingService extends BaseService {
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    ProfileMapper profileMapper;
    @Autowired
    AdvertOriginalDataMapper advertOriginalDataMapper;
    @Autowired
    RefreshTokenMapper refreshTokenMapper;
    @Autowired
    ErrorDateMapper errorDateMapper;
    @Autowired
    AmazonAdvBrandsCampaignReportMapper brandsCampaignReportMapper;
    @Autowired
    AmazonAdvBrandsAdGroupsReportMapper brandsAdGroupsReportMapper;
    @Autowired
    AmazonAdvBrandsKeywordReportMapper brandsKeywordReportMapper;
    @Autowired
    AmazonAdvBrandsTargetReportMapper brandsTargetReportMapper;
    @Autowired
    AmazonAdvBrandsSearchTermReportMapper brandsSearchTermReportMapper;
    @Autowired
    AdvOriginalDataReportHandleService advOriginalDataReportHandleService;
    /**
     * 错误重试次数
     */
    private final Integer MAX_ERROR_NUM = 5;


    /**
     * 获取指定时间的BrandsCampaignsReport数据--苏建东
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOriginalDataAdvBrandsCampaignsReport(String date, ShopAreaProfile shopAreaProfile) {
        String reportDate = date.replace("-", "");
        log.info("***********亚马逊广告api--shopId:" + shopAreaProfile.getShopId() + " areaId:" + shopAreaProfile.getAreaId() + "的BrandsCampaignsReport定时任务开始*************");
        //根据基本的配置信息去获取所有的原始数据
        StringBuffer errorMsg = new StringBuffer();
        Map<String, Object> params = new HashMap<String, Object>(2) {{
            put("segment", "placement");
            put("reportDate", reportDate);//时间格式YYYYMMDD
            put("metrics", "campaignName," +
                    "campaignId," +
                    "campaignStatus," +
                    "campaignBudget," +
                    "campaignBudgetType," +
                    "impressions," +
                    "clicks," +
                    "cost," +
                    "attributedDetailPageViewsClicks14d," +
                    "attributedSales14d," +
                    "attributedSales14dSameSKU," +
                    "attributedConversions14d," +
                    "attributedConversions14dSameSKU," +
                    "attributedOrdersNewToBrand14d," +
                    "attributedOrdersNewToBrandPercentage14d," +
                    "attributedOrderRateNewToBrand14d," +
                    "attributedSalesNewToBrand14d," +
                    "attributedSalesNewToBrandPercentage14d," +
                    "attributedUnitsOrderedNewToBrand14d," +
                    "attributedUnitsOrderedNewToBrandPercentage14d," +
                    "unitsSold14d," +
                    "dpv14d");
        }};
        Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
        Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
        String sellerId = shop.getSellerId();
        String regionCode = area.getRegionCode();
        RefreshTokenDO refreshTokenDO = refreshTokenMapper.selectRefreshTokenBySellerIdAndRegionCode(sellerId, regionCode);
        AmazonAdvertApiUtil.setAccessTokenToRedis(refreshTokenDO);
        log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsCampaignsReport定时任务开始*************");
        //创建事务还原点
        Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int errorNum = 0; errorNum < MAX_ERROR_NUM; errorNum++) {
            try {
                //将配置文件ID，商店的sellerID和需要拼接的URL字段和参数传入获取报表数据接口
                List<Map<String, Object>> lists = AmazonAdvertApiUtil.getReport(shopAreaProfile, CryptoUtil.decode(shop.getSellerId()), "hsa", "campaigns", params);
                if (null == lists) {
                    errorMsg.append("第").append(errorNum + 1).append("次，获取数据失败");
                    log.warn("profileid:" + shopAreaProfile.getProfileId() + "店铺：" + shop.getShopName() + errorMsg.toString());
                    Thread.sleep(1000L);
                    //若失败五次，则记录这个错误日期
                    if (errorNum == 4) {
                        ErrorDateDO errorDateDO = new ErrorDateDO();
                        errorDateDO.setSellerId(shop.getSellerId());
                        errorDateDO.setArea(area.getAdvertCountryCode());
                        errorDateDO.setErrorDate(reportDate);
                        errorDateDO.setType(7);
                        errorDateDO.setStatus(1);
                        errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorDateMapper.addErrorDate(errorDateDO);
                    }
                    continue;
                }
                //处理数据
                if (lists.size() == 0){
                    ErrorDateDO errorDateDO = new ErrorDateDO();
                    errorDateDO.setSellerId(shop.getSellerId());
                    errorDateDO.setArea(area.getAdvertCountryCode());
                    errorDateDO.setErrorDate(reportDate);
                    errorDateDO.setType(7);
                    errorDateDO.setStatus(2);
                    errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    errorDateMapper.addErrorDate(errorDateDO);
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的productAds在" + date + "的数据为空**********");
                    break;
                }
                Integer dataCount = brandsCampaignReportMapper.getDataCountFromBrandsCampaignReport(sellerId, area.getAdvertCountryCode(), date);
                if (lists.size() <= dataCount) {
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsCampaignsReport在" + date + "的数据已存在**********");
                    break;
                } else {
                    brandsCampaignReportMapper.deleteDataFromBrandsCampaignReportBySellerIdAreaDate(sellerId, area.getAdvertCountryCode(), date);
                }
                advOriginalDataReportHandleService.handleOriginalDataAdvBrandsCampaignsReport(lists, shop, area.getAdvertCountryCode(), date);
                break;
            } catch (Exception e) {
                //回滚事务
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
                e.printStackTrace();
                errorMsg.append("第").append(errorNum + 1).append("次出错,错误详情:").append(e);
            }
        }
        APICallsUtil.success();
        log.info("***********亚马逊广告api--BrandsCampaignsReport定时任务结束**********");
    }




    /**
     * 获取指定时间的BrandsAdGroupsReport数据--苏建东
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOriginalDataAdvBrandsAdGroupsReport(String date, ShopAreaProfile shopAreaProfile) {
        String reportDate = date.replace("-", "");
        log.info("***********亚马逊广告api--shopId:" + shopAreaProfile.getShopId() + " areaId:" + shopAreaProfile.getAreaId() + "的BrandsAdGroupsReport定时任务开始*************");
        //根据基本的配置信息去获取所有的原始数据
        StringBuffer errorMsg = new StringBuffer();
        Map<String, Object> params = new HashMap<String, Object>(2) {{
            put("reportDate", reportDate);//时间格式YYYYMMDD
            put("metrics", "campaignName," +
                    "campaignId," +
                    "campaignStatus," +
                    "campaignBudget," +
                    "campaignBudgetType," +
                    "adGroupName," +
                    "adGroupId," +
                    "impressions," +
                    "clicks," +
                    "cost," +
                    "attributedDetailPageViewsClicks14d," +
                    "attributedSales14d," +
                    "attributedSales14dSameSKU," +
                    "attributedConversions14d," +
                    "attributedConversions14dSameSKU," +
                    "attributedOrdersNewToBrand14d," +
                    "attributedOrdersNewToBrandPercentage14d," +
                    "attributedOrderRateNewToBrand14d," +
                    "attributedSalesNewToBrand14d," +
                    "attributedSalesNewToBrandPercentage14d," +
                    "attributedUnitsOrderedNewToBrand14d," +
                    "attributedUnitsOrderedNewToBrandPercentage14d," +
                    "unitsSold14d," +
                    "dpv14d");
        }};
        Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
        Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
        String sellerId = shop.getSellerId();
        String regionCode = area.getRegionCode();
        RefreshTokenDO refreshTokenDO = refreshTokenMapper.selectRefreshTokenBySellerIdAndRegionCode(sellerId, regionCode);
        AmazonAdvertApiUtil.setAccessTokenToRedis(refreshTokenDO);
        log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsAdGroupsReport定时任务开始*************");
        //创建事务还原点
        Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int errorNum = 0; errorNum < MAX_ERROR_NUM; errorNum++) {
            try {
                //将配置文件ID，商店的sellerID和需要拼接的URL字段和参数传入获取报表数据接口
                List<Map<String, Object>> lists = AmazonAdvertApiUtil.getReport(shopAreaProfile, CryptoUtil.decode(shop.getSellerId()), "hsa", "adGroups", params);
                if (null == lists) {
                    errorMsg.append("第").append(errorNum + 1).append("次，获取数据失败");
                    log.warn("profileid:" + shopAreaProfile.getProfileId() + "店铺：" + shop.getShopName() + errorMsg.toString());
                    Thread.sleep(1000L);
                    //若失败五次，则记录这个错误日期
                    if (errorNum == 4) {
                        ErrorDateDO errorDateDO = new ErrorDateDO();
                        errorDateDO.setSellerId(shop.getSellerId());
                        errorDateDO.setArea(area.getAdvertCountryCode());
                        errorDateDO.setErrorDate(reportDate);
                        errorDateDO.setType(8);
                        errorDateDO.setStatus(1);
                        errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorDateMapper.addErrorDate(errorDateDO);
                    }
                    continue;
                }
                //处理
                if (lists.size() == 0){
                    ErrorDateDO errorDateDO = new ErrorDateDO();
                    errorDateDO.setSellerId(shop.getSellerId());
                    errorDateDO.setArea(area.getAdvertCountryCode());
                    errorDateDO.setErrorDate(reportDate);
                    errorDateDO.setType(8);
                    errorDateDO.setStatus(2);
                    errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    errorDateMapper.addErrorDate(errorDateDO);
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的productAds在" + date + "的数据为空**********");
                    break;
                }
                Integer dataCount = brandsAdGroupsReportMapper.getDataCountFromBrandsAdGroupsReport(sellerId, area.getAdvertCountryCode(), date);
                if (lists.size() <= dataCount) {
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsAdGroupsReport在" + date + "的数据已存在**********");
                    break;
                } else {
                    brandsAdGroupsReportMapper.deleteDataFromBrandsAdGroupsReportBySellerIdAreaDate(sellerId, area.getAdvertCountryCode(), date);
                }
                advOriginalDataReportHandleService.handleOriginalDataAdvBrandsAdGroupsReport(lists, shop, area.getAdvertCountryCode(), date);
                break;
            } catch (Exception e) {
                //回滚事务
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
                e.printStackTrace();
                errorMsg.append("第").append(errorNum + 1).append("次出错,错误详情:").append(e);
            }
        }
        APICallsUtil.success();
        log.info("***********亚马逊广告api--BrandsAdGroupsReport定时任务结束**********");
    }



    /**
     * 获取指定时间的BrandsKeywordsReport数据--苏建东
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOriginalDataAdvBrandsKeywordsReport(String date, ShopAreaProfile shopAreaProfile) {
        String reportDate = date.replace("-", "");
        log.info("***********亚马逊广告api--shopId:" + shopAreaProfile.getShopId() + " areaId:" + shopAreaProfile.getAreaId() + "的BrandsKeywordsReport定时任务开始*************");
        //根据基本的配置信息去获取所有的原始数据
        StringBuffer errorMsg = new StringBuffer();
        Map<String, Object> params = new HashMap<String, Object>(3) {{
            //put("segment", "query");
            put("reportDate", reportDate);//时间格式YYYYMMDD
            put("metrics", "campaignName," +
                    "campaignId," +
                    "campaignStatus," +
                    "campaignBudget," +
                    "campaignBudgetType," +
                    "adGroupName," +
                    "adGroupId," +
                    "keywordId," +
                    "keywordStatus," +
                    "keywordBid," +
                    "keywordText," +
                    "matchType," +
                    "impressions," +
                    "clicks," +
                    "cost," +
                    "attributedDetailPageViewsClicks14d," +
                    "attributedSales14d," +
                    "attributedSales14dSameSKU," +
                    "attributedConversions14d," +
                    "attributedConversions14dSameSKU," +
                    "attributedOrdersNewToBrand14d," +
                    "attributedOrdersNewToBrandPercentage14d," +
                    "attributedOrderRateNewToBrand14d," +
                    "attributedSalesNewToBrand14d," +
                    "attributedSalesNewToBrandPercentage14d," +
                    "attributedUnitsOrderedNewToBrand14d," +
                    "attributedUnitsOrderedNewToBrandPercentage14d," +
                    "unitsSold14d," +
                    "dpv14d");
        }};
        Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
        Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
        String sellerId = shop.getSellerId();
        String regionCode = area.getRegionCode();
        RefreshTokenDO refreshTokenDO = refreshTokenMapper.selectRefreshTokenBySellerIdAndRegionCode(sellerId, regionCode);
        AmazonAdvertApiUtil.setAccessTokenToRedis(refreshTokenDO);
        log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsKeywordsReport定时任务开始*************");
        //创建事务还原点
        Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int errorNum = 0; errorNum < MAX_ERROR_NUM; errorNum++) {
            try {
                //将配置文件ID，商店的sellerID和需要拼接的URL字段和参数传入获取报表数据接口
                List<Map<String, Object>> lists = AmazonAdvertApiUtil.getReport(shopAreaProfile, CryptoUtil.decode(shop.getSellerId()), "hsa", "keywords", params);
                if (null == lists) {
                    errorMsg.append("第").append(errorNum + 1).append("次，获取数据失败");
                    log.warn("profileid:" + shopAreaProfile.getProfileId() + "店铺：" + shop.getShopName() + errorMsg.toString());
                    Thread.sleep(1000L);
                    //若失败五次，则记录这个错误日期
                    if (errorNum == 4) {
                        ErrorDateDO errorDateDO = new ErrorDateDO();
                        errorDateDO.setSellerId(shop.getSellerId());
                        errorDateDO.setArea(area.getAdvertCountryCode());
                        errorDateDO.setErrorDate(reportDate);
                        errorDateDO.setType(9);
                        errorDateDO.setStatus(1);
                        errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorDateMapper.addErrorDate(errorDateDO);
                    }
                    continue;
                }
                //处理
                if (lists.size() == 0){
                    ErrorDateDO errorDateDO = new ErrorDateDO();
                    errorDateDO.setSellerId(shop.getSellerId());
                    errorDateDO.setArea(area.getAdvertCountryCode());
                    errorDateDO.setErrorDate(reportDate);
                    errorDateDO.setType(9);
                    errorDateDO.setStatus(2);
                    errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    errorDateMapper.addErrorDate(errorDateDO);
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的productAds在" + date + "的数据为空**********");
                    break;
                }
                Integer dataCount = brandsKeywordReportMapper.getDataCountFromBrandsKeywordsReport(sellerId, area.getAdvertCountryCode(), date);
                if (lists.size() == dataCount) {
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsKeywordsReport在" + date + "的数据已存在**********");
                    break;
                } else {
                    brandsKeywordReportMapper.deleteDataFromBrandsKeywordsReportBySellerIdAreaDate(sellerId, area.getAdvertCountryCode(), date);
                }
                advOriginalDataReportHandleService.handleOriginalDataAdvBrandsKeywordsReport(lists, shop, area.getAdvertCountryCode(), date);
                break;
            } catch (Exception e) {
                //回滚事务
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
                e.printStackTrace();
                errorMsg.append("第").append(errorNum + 1).append("次出错,错误详情:").append(e);
            }
        }
        APICallsUtil.success();
        log.info("***********亚马逊广告api--BrandsKeywordsReport定时任务结束**********");
    }


    /**
     * 获取指定时间的BrandsTargetsReport数据--苏建东
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOriginalDataAdvBrandsTargetsReport(String date, ShopAreaProfile shopAreaProfile) {
        String reportDate = date.replace("-", "");
        log.info("***********亚马逊广告api--shopId:" + shopAreaProfile.getShopId() + " areaId:" + shopAreaProfile.getAreaId() + "的BrandsTargetsReport定时任务开始*************");
        //根据基本的配置信息去获取所有的原始数据
        StringBuffer errorMsg = new StringBuffer();
        Map<String, Object> params = new HashMap<String, Object>(3) {{
            put("reportDate", reportDate);//时间格式YYYYMMDD
            put("metrics", "campaignName," +
                    "campaignId," +
                    "adGroupName," +
                    "adGroupId," +
                    "campaignBudgetType," +
                    "campaignStatus," +
                    "targetId," +
                    "targetingExpression," +
                    "targetingType," +
                    "targetingText," +
                    "impressions," +
                    "clicks," +
                    "cost," +
                    "attributedDetailPageViewsClicks14d," +
                    "attributedSales14d," +
                    "attributedSales14dSameSKU," +
                    "attributedConversions14d," +
                    "attributedConversions14dSameSKU," +
                    "attributedOrdersNewToBrand14d," +
                    "attributedOrdersNewToBrandPercentage14d," +
                    "attributedOrderRateNewToBrand14d," +
                    "attributedSalesNewToBrand14d," +
                    "attributedSalesNewToBrandPercentage14d," +
                    "attributedUnitsOrderedNewToBrand14d," +
                    "attributedUnitsOrderedNewToBrandPercentage14d," +
                    "unitsSold14d," +
                    "dpv14d");
        }};
        Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
        Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
        String sellerId = shop.getSellerId();
        String regionCode = area.getRegionCode();
        RefreshTokenDO refreshTokenDO = refreshTokenMapper.selectRefreshTokenBySellerIdAndRegionCode(sellerId, regionCode);
        AmazonAdvertApiUtil.setAccessTokenToRedis(refreshTokenDO);
        log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsTargetsReport定时任务开始*************");
        //创建事务还原点
        Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int errorNum = 0; errorNum < MAX_ERROR_NUM; errorNum++) {
            try {
                //将配置文件ID，商店的sellerID和需要拼接的URL字段和参数传入获取报表数据接口
                List<Map<String, Object>> lists = AmazonAdvertApiUtil.getReport(shopAreaProfile, CryptoUtil.decode(shop.getSellerId()), "hsa", "targets", params);
                if (null == lists) {
                    errorMsg.append("第").append(errorNum + 1).append("次，获取数据失败");
                    log.warn("profileid:" + shopAreaProfile.getProfileId() + "店铺：" + shop.getShopName() + errorMsg.toString());
                    Thread.sleep(1000L);
                    //若失败五次，则记录这个错误日期
                    if (errorNum == 4) {
                        ErrorDateDO errorDateDO = new ErrorDateDO();
                        errorDateDO.setSellerId(shop.getSellerId());
                        errorDateDO.setArea(area.getAdvertCountryCode());
                        errorDateDO.setErrorDate(reportDate);
                        errorDateDO.setType(10);
                        errorDateDO.setStatus(1);
                        errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorDateMapper.addErrorDate(errorDateDO);
                    }
                    continue;
                }
                //处理
                if (lists.size() == 0){
                    ErrorDateDO errorDateDO = new ErrorDateDO();
                    errorDateDO.setSellerId(shop.getSellerId());
                    errorDateDO.setArea(area.getAdvertCountryCode());
                    errorDateDO.setErrorDate(reportDate);
                    errorDateDO.setType(10);
                    errorDateDO.setStatus(2);
                    errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    errorDateMapper.addErrorDate(errorDateDO);
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的productAds在" + date + "的数据为空**********");
                    break;
                }
                Integer dataCount = brandsTargetReportMapper.getDataCountFromBrandsTargetsReport(sellerId, area.getAdvertCountryCode(), date);
                if (lists.size() == dataCount) {
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsTargetsReport在" + date + "的数据已存在**********");
                    break;
                } else {
                    brandsTargetReportMapper.deleteDataFromBrandsTargetsReportBySellerIdAreaDate(sellerId, area.getAdvertCountryCode(), date);
                }
                advOriginalDataReportHandleService.handleOriginalDataAdvBrandsTargetsReport(lists, shop, area.getAdvertCountryCode(), date);
                break;
            } catch (Exception e) {
                //回滚事务
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
                e.printStackTrace();
                errorMsg.append("第").append(errorNum + 1).append("次出错,错误详情:").append(e);
            }
        }
        APICallsUtil.success();
        log.info("***********亚马逊广告api--BrandsTargetsReport定时任务结束**********");
    }




    /**
     * 获取指定时间的BrandsSearchTermReport数据--苏建东
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOriginalDataAdvBrandsSearchTermReport(String date, ShopAreaProfile shopAreaProfile) {
        String reportDate = date.replace("-", "");
        log.info("***********亚马逊广告api--shopId:" + shopAreaProfile.getShopId() + " areaId:" + shopAreaProfile.getAreaId() + "的BrandsSearchTermReport定时任务开始*************");
        //根据基本的配置信息去获取所有的原始数据
        StringBuffer errorMsg = new StringBuffer();
        Map<String, Object> params = new HashMap<String, Object>(3) {{
            put("segment", "query");
            put("reportDate", reportDate);//时间格式YYYYMMDD
            put("metrics", "campaignName," +
                    "campaignId," +
                    "campaignStatus," +
                    "campaignBudget," +
                    "campaignBudgetType," +
                    "adGroupName," +
                    "adGroupId," +
                    "keywordId," +
                    "keywordStatus," +
                    "keywordBid," +
                    "keywordText," +
                    "matchType," +
                    "impressions," +
                    "clicks," +
                    "cost," +
                    "attributedSales14d," +
                    "attributedConversions14d");
        }};
        Area area = areaMapper.getOneInfoByAreaId(shopAreaProfile.getAreaId());
        Shop shop = shopMapper.getOneInfoByShopId(shopAreaProfile.getShopId());
        String sellerId = shop.getSellerId();
        String regionCode = area.getRegionCode();
        RefreshTokenDO refreshTokenDO = refreshTokenMapper.selectRefreshTokenBySellerIdAndRegionCode(sellerId, regionCode);
        AmazonAdvertApiUtil.setAccessTokenToRedis(refreshTokenDO);
        log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsSearchTermReport定时任务开始*************");
        //创建事务还原点
        Object savepoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (int errorNum = 0; errorNum < MAX_ERROR_NUM; errorNum++) {
            try {
                //将配置文件ID，商店的sellerID和需要拼接的URL字段和参数传入获取报表数据接口
                List<Map<String, Object>> lists = AmazonAdvertApiUtil.getReport(shopAreaProfile, CryptoUtil.decode(shop.getSellerId()), "hsa", "keywords", params);
                if (null == lists) {
                    errorMsg.append("第").append(errorNum + 1).append("次，获取数据失败");
                    log.warn("profileid:" + shopAreaProfile.getProfileId() + "店铺：" + shop.getShopName() + errorMsg.toString());
                    Thread.sleep(1000L);
                    //若失败五次，则记录这个错误日期
                    if (errorNum == 4) {
                        ErrorDateDO errorDateDO = new ErrorDateDO();
                        errorDateDO.setSellerId(shop.getSellerId());
                        errorDateDO.setArea(area.getAdvertCountryCode());
                        errorDateDO.setErrorDate(reportDate);
                        errorDateDO.setType(11);
                        errorDateDO.setStatus(1);
                        errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        errorDateMapper.addErrorDate(errorDateDO);
                    }
                    continue;
                }
                //处理
                if (lists.size() == 0){
                    ErrorDateDO errorDateDO = new ErrorDateDO();
                    errorDateDO.setSellerId(shop.getSellerId());
                    errorDateDO.setArea(area.getAdvertCountryCode());
                    errorDateDO.setErrorDate(reportDate);
                    errorDateDO.setType(11);
                    errorDateDO.setStatus(2);
                    errorDateDO.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    errorDateMapper.addErrorDate(errorDateDO);
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的productAds在" + date + "的数据为空**********");
                    break;
                }
                Integer dataCount = brandsSearchTermReportMapper.getDataCountFromBrandsSearchTermReport(sellerId, area.getAdvertCountryCode(), date);
                if (lists.size() == dataCount) {
                    log.info("***********" + shop.getShopName() + "的" + area.getAreaName() + "的BrandsSearchTermReport在" + date + "的数据已存在**********");
                    break;
                } else {
                    brandsSearchTermReportMapper.deleteDataFromBrandsSearchTermReportBySellerIdAreaDate(sellerId, area.getAdvertCountryCode(), date);
                }
                advOriginalDataReportHandleService.handleOriginalDataAdvBrandsSearchTermReport(lists, shop, area.getAdvertCountryCode(), date);
                break;
            } catch (Exception e) {
                //回滚事务
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savepoint);
                e.printStackTrace();
                errorMsg.append("第").append(errorNum + 1).append("次出错,错误详情:").append(e);
            }
        }
        APICallsUtil.success();
        log.info("***********亚马逊广告api--BrandsSearchTermReport定时任务结束**********");
    }


    /**
     * 打印出错信息
     *
     * @param errorMsg
     */
    private void logWarnErrorMsg(String errorMsg, String shopName) {
        log.warn("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓定时任务出错↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
        log.warn("×××××亚马逊广告api×××定时任务出错×××" +
                "×××××错误详情:" + errorMsg);
        log.warn("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑定时任务出错↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
        DataGetErrorRecord record = new DataGetErrorRecord();
        record.setShop(shopName);
        record.setArea("所有旗下国家代码");
        String date = DateUtil.getFetureDate(0) + " 08:00:00";
        record.setDate(date);
        record.setName("亚马逊广告api定时任务");
        //是否处理，0:未处理,1:已处理',
        record.setIsHandle(0);
        //类型:亚马逊广告api定时任务
        record.setType(2);
        record.setRemark("亚马逊广告api定时任务出错,任务名称:"
                + "出错的时间:" + date
                + "错误详情:" + errorMsg);
        record.setCreateTime(DateUtil.getFutureDateTime(0));
        baseInsert(record);
    }
}
